﻿using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using ExcelDna.Integration;
using ExcelDna.Integration.CustomUI;
using FastLogAsync;

namespace ExcelDnaDemo
{
    /// <summary>
    /// Load custom Excel Fluent/Ribbon
    /// </summary>
    [ComVisible(true)]
    [Guid(AppSettings.RibbonGUID), ProgId(AppSettings.RibbonProgID)]
    public class RibbonUI : ExcelRibbon
    {
        private static IRibbonUI customRibbon;             //记录IRibbonUI对象  

        #region Fluent/Ribbon UI
        //https://msdn.microsoft.com/en-us/library/aa722523.aspx  //回调
        //https://msdn.microsoft.com/zh-cn/library/office/ee691833(v=office.14).aspx

        //Custom UI XML Markup Specification
        //https://docs.microsoft.com/en-us/openspecs/office_standards/ms-customui/31f152d6-2a5d-4b50-a867-9dbc6d01aa43?redirectedfrom=MSDN

        /// <summary>
        /// ribbon callback, get IRibbonUI object.
        /// </summary>
        public void ribbonLoaded(IRibbonUI ribbon)
        {            
            Log.Info("ribbonLoaded");
            customRibbon = ribbon;
            //customRibbon.ActivateTab("ExcelDnaDemoTab");
            //此处不能启动CTP
            
        }

        /// <summary>
        /// read CustomUI.xml, xml file must be UTF-8 encode and Embedded resources.
        /// </summary>
        public override string GetCustomUI(string uiName)
        {
            string ribbonxml = string.Empty;
            try
            {
                Log.Info($"GetCustomUI uiName:{uiName}");

                if (ExcelDnaUtil.ExcelVersion >= 14)
                    ribbonxml = ResourceHelper.GetResourceText("CustomUI14.xml");  //CustomUI14.xml需要设成嵌入资源。
                else
                    ribbonxml = ResourceHelper.GetResourceText("CustomUI12.xml");  //CustomUI12.xml需要设成嵌入资源。   
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return ribbonxml;
        }

        /// <summary>
        /// Ribbon callback，load image in XML element
        /// </summary>
        public override object LoadImage(string imageId)
        {
            return ResourceHelper.GetResourceBitmap(imageId);
        }

        /// <summary>
        /// ribbon callback.
        /// </summary>
        public void button_Click(IRibbonControl control)
        {
            if (ExcelisEditing())
            {
                MessageBox.Show($"工作表处于编辑状态时请勿点击功能按钮!（按Esc、回车或点击其它单元格可退出编辑状态）", "提示",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning,
                                MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
                return;

                //SendKeys.SendWait("{ENTER}");
            }
            
            switch (control.Id)
            {
                case "ShowCTP":
                    //customRibbon.Invalidate();
                    ShowCTP();
                    break;
                
                case "About":
                    dynamic app = ExcelDnaUtil.Application;
                    MessageBox.Show($"Application.Version={app.Version},ExcelDna Version={ExcelDnaUtil.ExcelVersion},ET={ExcelDnaUtil.IsET}");
                    break;

                default:
                    MessageBox.Show("Hello:" + control.Id);
                    break;
            }
        }

        private bool ExcelisEditing()
        {
            #region 判断编辑状态
            /*
            Application ExcelApp = ExcelDnaUtil.Application as Application;
            if (!Application.Ready) return true;            
            if (Application.Interactive == false) return false;
            try
            {
                Application.Interactive = false;
                pplication.Interactive = true;
            }
            catch
            {
                return true;
            }
            */
            return false;            
            #endregion 判断编辑状态
        }        
        
        #endregion Fluent/Ribbon UI

        #region CustomTaskPane
        public void OnShowCTP(IRibbonControl control)
        {
            Log.Info("OnShowCTP");
            ShowCTP();
        }        
        private void ShowCTP()
        {
            Log.Info("CTPManager.ShowCTP");
            int hwnd = GetActivewindowHwnd();
            CTPManager.Instance.ShowCTP(hwnd);
            Log.Info($"CTPManager.Instance.ShowCTP(hwnd) finished");
        }

        public void OnDeleteCTP(IRibbonControl control)
        {
            CTPManager.Instance.DeleteCTP(GetActivewindowHwnd());
        }
        private int GetActivewindowHwnd()
        {
            Log.Info("GetActivewindowHwnd");
            int hwnd = 0;
            if (ExcelDnaUtil.IsET) return hwnd;  //WPS个人版不是SDI。

            //Office 2013 is SDI(single document interface)
            //每个工作簿有一个单独的Window句柄，也有一个单独的CTP。
            //所以，要管理CTP需要借助ActiveWindow.Hwnd
            //通过Hwnd来判断当前的CTP。

            //在本Demo中，因为没有引用Excel或WPS库，所以不能得到ActiveWindow.Hwnd。
            //以下代码屏蔽，待引用Excel或者WPS库之后再加上获取Hwnd的代码。
            if (ExcelDnaUtil.ExcelVersion > 14)     //Excel2013 版本号是15.0
            {                
            //    ExcelPIA.Window activewin = (ExcelDnaUtil.Application as ExcelPIA.Application).ActiveWindow;
            //    if (activewin != null) hwnd = activewin.Hwnd;
            }
            return hwnd;
        }
        #endregion CustomTaskPane
    }
}
